import {Button, Form, Input, Layout, Modal, Popconfirm,} from "antd";
import {
    ArrowDownOutlined,
    ArrowUpOutlined,
    DeleteOutlined,
    DiscordOutlined,
    FormOutlined,
    QuestionCircleOutlined
} from "@ant-design/icons";
import {useEffect, useState} from 'react'
import {useSelector} from "react-redux";
import {queryTypeApi} from "../../interface/typeApi";
import { Radio } from 'antd';
import Mock from "mockjs";

function SideBar({onSideFun=(val)=>{}}){
    //获取store中theme的状态
    const globalTheme = useSelector((state) => state.theme);
    const [currentId, setCurrentId] = useState('1');
    const [menuList, setMenuList] = useState([]);
    const [iconShowIndex, setIconShowIndex] = useState(-1);
    const [formIndex, setFormIndex] = useState({});
    const [isModalOpen, setIsShowModal] = useState(false);
    const [modalTitle, setModalTitle] = useState('新增类别');
    // 添加 ref
    const [formRef] = Form.useForm();
    useEffect(() => {
        queryTypeApi({}).then((res) => {
            if (res.code === 200) {
                setMenuList(res.data.records);
                if (res.data.records.length > 0) {
                    setCurrentId(res.data.records[0]?.id);
                    onSideFun(res.data.records[0] || {});
                }
            }
        })
    }, []);

    const ButtonStyle = {
        height: '48px',
        display: 'flex',
        width: '99.9%',
        alignItems: 'center',
        padding: '0 8px',
        background: globalTheme.dark ? '#141414': '#ffffff',
    }
    const sideMenuStyle = {
        width: '99.9%',
        height: 'calc(100% - 48px)',
        padding: '0 8px',
        background: globalTheme.dark ? '#1d1d1d': '#fafafa',
    }
    const menuItemStyle = {
        display: 'flex',
        width: '100%',
        justifyContent: 'space-between',
        alignItems: 'center',
    }
    const submitFun =(row,index,type) => {
        switch(type){
            case 'up':
                const sItemUp = menuList[index-1];
                menuList[index-1]=row;
                menuList[index]=sItemUp;
                setMenuList([...menuList]);
                break;
            case 'down':
                const sItemDown = menuList[index+1];
                menuList[index+1]=row;
                menuList[index]=sItemDown;
                setMenuList([...menuList]);
                break;
            case 'edit':
                setFormIndex(index);
                formRef.setFieldsValue(row);
                setIsShowModal(true);
                setModalTitle('编辑类别');
                break;
            case 'delete':
                const newList = [...menuList];
                if ((menuList.length-1) === index) {
                    onSideFun(newList[0] || {});
                }else if (menuList.length === 1) {
                    return window.alert("不可删除！");
                }else{
                 if (row.id === currentId) {
                     setCurrentId(newList[index+1]?.id || '1')
                     onSideFun(newList[index+1] || {});
                 }
                }
                newList.splice(index, 1); // 删除指定索引的项
                setMenuList(newList);
                break;
            case 'save':
                formRef.validateFields().then((res) => {
                    setMenuList(prevMenuList => {
                        const newList = [...prevMenuList];
                        newList[formIndex] = {
                            ...newList[formIndex],
                            name: res.name,
                            status: res.status
                        };
                        // 推送逻辑放在 setState 回调中
                        if (newList[formIndex].id === currentId) {
                            onSideFun(newList[formIndex]);
                        }
                        return newList;
                    });
                    setIsShowModal(false);
                }).catch((err) => {})
                break;
            case 'add':
                setIsShowModal(true);
                setModalTitle('新增类别');
                formRef.setFieldsValue({
                    name: ``,
                    status: 1,
                })
                break;
            case 'saveAdd':
                formRef.validateFields().then((res) => {
                    let newInfo ={
                        id: Math.random(), // 自增ID
                        name: res.name,
                        status: res.status,
                        children: [], // 50%概率有子节点
                        disabled:false, // 20%概率禁用
                        createTime: '' // 随机生成创建时间
                    }
                    menuList.push(newInfo);
                    setMenuList([...menuList]);
                    setIsShowModal(false)
                })
        }
    };
    return(
        <Layout>
            <div className='side-bar'>
                <div style={ButtonStyle}>
                    <Button type='primary' onClick={(e)=>{e.preventDefault();e.stopPropagation();submitFun('','','add')}}>新增类别</Button>
                </div>
              <div style={sideMenuStyle}>
                  {
                      menuList.map((item,index) => (
                         <Button
                             key={item.id}
                             type={item.id === currentId ? 'primary' : 'default'}
                             style={{width: '100%', height: '40px', marginTop: '8px'}}
                             onClick={(e)=>{e.preventDefault();onSideFun(item);setCurrentId(item.id)}}
                             onMouseEnter={()=>{setIconShowIndex(index)}}
                             onMouseLeave={()=>{setIconShowIndex(-1)}}
                         >
                             <div style={menuItemStyle}>
                                 <div className='flex items-center'>
                                     <DiscordOutlined/>
                                     <div className='ml-4 w-16 relative truncate'>{item.name}</div>
                                 </div>
                                 <div className='flex flex-row items-center' style={(iconShowIndex === index || currentId === item.id) ? {}:{display: 'none'}}>
                                     <div className='ml-4' style={{transition: 'all 0.3s'}}
                                          onMouseEnter={(e) => e.currentTarget.style.transform = 'scale(1.3)'}
                                          onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}
                                          onClick={(e)=>{e.stopPropagation();e.preventDefault();submitFun(item,index,'up')}}>
                                         {index===0? <></>:<ArrowUpOutlined />}
                                     </div>
                                     <div className='ml-4' style={{transition: 'all 0.3s'}}
                                          onMouseEnter={(e) => e.currentTarget.style.transform = 'scale(1.3)'}
                                          onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}
                                          onClick={(e) => {e.stopPropagation();e.preventDefault();submitFun(item,index,'down')}}>
                                         {index===menuList.length-1? <></>:<ArrowDownOutlined />}
                                     </div>
                                     <div className='ml-4' style={{transition: 'all 0.3s'}}
                                          onMouseEnter={(e) => e.currentTarget.style.transform = 'scale(1.3)'}
                                          onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}
                                          onClick={(e) => {e.stopPropagation();e.preventDefault(); submitFun(item,index,'edit')}}>
                                         <FormOutlined />
                                     </div>
                                     <Popconfirm
                                         title="温馨提示"
                                         description="是否确认执行删除?"
                                         icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
                                         onConfirm={(e)=>{e.preventDefault();e.stopPropagation(); submitFun(item,index,'delete')}}
                                     >
                                         <div className='ml-4' style={{transition: 'all 0.3s'}}
                                              onMouseEnter={(e) => e.currentTarget.style.transform = 'scale(1.3)'}
                                              onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}>
                                             <DeleteOutlined />
                                         </div>
                                     </Popconfirm>

                                 </div>
                             </div>
                          </Button>
                      ))
                  }
              </div>
            </div>
            <Modal title={modalTitle}
                   open={isModalOpen}
                   width={350}
                   onOk={()=> {modalTitle.includes('新增')? submitFun('','', 'saveAdd'):submitFun('','', 'save')}}
                   onCancel={()=>{setIsShowModal(false);}}>
                <Form
                    name="basic"
                    layout='vertical'
                    initialValues={{ remember: true }}
                    autoComplete="off"
                    form={formRef}
                >
                    <Form.Item label="设计需求类别名称" name="name" rules={[{ required: true, message: '字段不能为空!' }]}>
                        <Input />
                    </Form.Item>

                    <Form.Item name="status" label="状态" rules={[{ required: true, message: '字段不能为空!' }]}>
                        <Radio.Group
                            options={[{ value: 1, label: '启用' },{ value: 0, label: '禁用' }]}
                        />
                    </Form.Item>
                </Form>
            </Modal>
        </Layout>
    )
}

export default SideBar;